package topic.activity;

import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.example.xuegengwang.xuegengwang.R;
import com.google.gson.Gson;
import com.makeramen.roundedimageview.RoundedImageView;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import common.BaseActivity;
import common.Constant;
import https.InterNetController;
import in.srain.cube.views.ptr.PtrFrameLayout;
import mainFragment.adapter.MyGridViewAdapter;
import topic.adapter.TopicDetailAdapter;
import topic.bean.TopicDetailBean;
import personalPage.activity.PersonalPage;
import utils.MyLogUtils;
import utils.SPUtils;
import utils.ShowImageUtils;
import view.MyConfirmDialog;
import view.MyGridView;
import view.MyImageLoader;
import view.MyPtrRefresh_LoadView;

/**
 * Created by Administrator on 2017/3/22.
 * 帖子详情
 */

@ContentView(R.layout.topic_detail)
public class TopicDetail extends BaseActivity implements View.OnClickListener {
    @ViewInject(R.id.topic_detail_back)
    private ImageView topic_detail_back;
    @ViewInject(R.id.topic_detail_title)
    private TextView topic_detail_title;
    @ViewInject(R.id.topic_detail_refresh_load_Layout)
    private MyPtrRefresh_LoadView topic_detail_refresh_load_Layout;
    @ViewInject(R.id.topic_detail_lv)
    private ListView myListView;
    @ViewInject(R.id.topic_detail_comment_layout)
    private RelativeLayout topic_detail_comment_layout;
//    @ViewInject(R.id.topic_detail_share_ima)
//    private ImageView topic_detail_share_ima;
    private View headerView;
    private TopicDetailAdapter topicDetailAdapter;
    private ArrayList<TopicDetailBean.CommentListBean>commentList;
    private String blogid;
    private int page = 1;
    //头部控件
    private RelativeLayout college_topic_item_headLayout;
    private TextView college_topic_item_name;
    private TextView college_topic_item_addr;
    private TextView college_topic_item_content;
    private TextView college_topic_item_time;
    private TextView college_topic_item_zan;
    private TextView college_topic_item_comment;
    private TextView college_topic_item_delete;
    //头部控件
    private RoundedImageView college_topic_item_headIma;
    private MyGridView myGridView;
    private MyGridViewAdapter myGridViewAdapter;


    private int zan;//获取当前的赞
    private int comment;//获取当前评论数
    private boolean is_praised;//是否已经点赞
    private boolean is_deleted;//是否删除这条博客

    private TopicDetailBean topicDetailBean;

    private boolean firstOpen;
    private final int ON_REFRESH = 0;
    private final int ON_LOAD = 4;
    private final int ZAN = 1;
    private final int DELETE_BLOG = 2;
    private final int DELETE_COMMENT = 3;
    private static final String TAG = "TopicDetail";
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case Constant.ERROR_CODE_SUCCESS://成功返回
                    if (msg.arg1 == DELETE_BLOG) {
                        MyLogUtils.e(TAG, "删除成功");
                        is_deleted = true;
                        setReturn();
                    } else if (msg.arg1 == DELETE_COMMENT) {
                        MyLogUtils.e(TAG, "删除成功");
                        comment--;
                        commentList.remove(msg.arg2);
                        myGridViewAdapter.notifyDataSetChanged();
                    } else {
                        final int color = TopicDetail.this.getResources().getColor(R.color.common_color);
                        final int color1 = TopicDetail.this.getResources().getColor(R.color.text_color1);
                        final Drawable drawable = TopicDetail.this.getResources().getDrawable(R.mipmap.college_topic_item_zan_ima);
                        final Drawable drawable1 = TopicDetail.this.getResources().getDrawable(R.mipmap.college_topic_item_zan_ima1);
                        drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                        drawable1.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                        switch (msg.arg1) {
                            case ON_REFRESH://获得信息
                                Gson gson = new Gson();
                                topicDetailBean = gson.fromJson((String) msg.obj, TopicDetailBean.class);
                                if (topicDetailBean != null) {
                                    //获取帖子内容
                                    final TopicDetailBean.BlogBean blog = topicDetailBean.getBlog();
                                    if (blog != null) {
                                        college_topic_item_name.setText(blog.getNickname());
                                        college_topic_item_content.setText(blog.getContent());
                                        college_topic_item_time.setText(blog.getTime());
                                        zan = Integer.parseInt(blog.getPrise());
                                        college_topic_item_zan.setText(blog.getPrise());
                                        if (SPUtils.getSharedPreferences().getString(Constant.USER_ID, "").equals(topicDetailBean.getBlog().getUserid())) {
                                            //评论自己
                                            topic_detail_comment_layout.setVisibility(View.GONE);
                                        } else {
                                            topic_detail_comment_layout.setVisibility(View.VISIBLE);
                                        }
                                        if (0 == topicDetailBean.getBlog().getShowdelete()) {
                                            //不能删除
                                            college_topic_item_delete.setVisibility(View.GONE);
                                        } else {
                                            //可以删除
                                            college_topic_item_delete.setVisibility(View.VISIBLE);
                                            college_topic_item_delete.setOnClickListener(new View.OnClickListener() {
                                                @Override
                                                public void onClick(View v) {
                                                    final MyConfirmDialog myConfirmDialog = new MyConfirmDialog(TopicDetail.this, R.style.confirmDialog, "确认删除?");
                                                    myConfirmDialog.show();
                                                    myConfirmDialog.setConfirmListener(new MyConfirmDialog.ConfirmListener() {
                                                        @Override
                                                        public void confirm() {
                                                            deleteBlog(topicDetailBean.getBlog().getBlogid(), handler);
                                                        }
                                                    });

                                                }
                                            });
                                        }
                                        if (!TextUtils.isEmpty(topicDetailBean.getBlog().getTitle())) {
                                            topic_detail_title.setText(topicDetailBean.getBlog().getTitle());
                                        }
                                        college_topic_item_addr.setText(blog.getCity());
                                        if (blog.getPrised() != 0) {
                                            //已经赞了
                                            is_praised = true;
                                            college_topic_item_zan.setTextColor(color);
                                            college_topic_item_zan.setCompoundDrawables(drawable1, null, null, null);
                                        } else {
                                            //还没赞
                                            is_praised = false;
                                            college_topic_item_zan.setTextColor(color1);
                                            college_topic_item_zan.setCompoundDrawables(drawable, null, null, null);
                                        }
                                        comment = Integer.parseInt(blog.getComment());
                                        college_topic_item_comment.setText(blog.getComment());
                                        MyImageLoader.showImage(blog.getHeadimgurl(), college_topic_item_headIma);//设置头像
                                        myGridViewAdapter = new MyGridViewAdapter(TopicDetail.this, blog.getImages());
                                        myGridView.setAdapter(myGridViewAdapter);
                                        myGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                                            @Override
                                            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                                                //点击图片
                                                ShowImageUtils showImageUtils = new ShowImageUtils();
                                                showImageUtils.showImageUtils(TopicDetail.this, view, blog.getImages(), position);
                                            }
                                        });
                                        firstOpen = false;
                                    }
                                    //获取评论列表
                                    List<TopicDetailBean.CommentListBean> commentList1 = topicDetailBean.getCommentList();
                                    //重新加载
                                    commentList.clear();
                                    if (commentList1 != null) {
                                        if (commentList1.size() > 0) {
                                            for (int i = 0; i < commentList1.size(); i++) {
                                                commentList.add(commentList1.get(i));
                                            }
                                        }
                                    }
                                    topicDetailAdapter.notifyDataSetChanged();
                                }
                                topic_detail_refresh_load_Layout.OnRefreshComplete();
                                break;
                            case ON_LOAD:
                                Gson gson1 = new Gson();
                                topicDetailBean = gson1.fromJson((String) msg.obj, TopicDetailBean.class);
                                //获取评论列表
                                List<TopicDetailBean.CommentListBean> commentList1 = topicDetailBean.getCommentList();
                                if (commentList1 != null) {
                                    if (commentList1.size() > 0) {
                                        for (int i = 0; i < commentList1.size(); i++) {
                                            commentList.add(commentList1.get(i));
                                        }
                                    } else {
                                        page--;
                                    }
                                }
                                topic_detail_refresh_load_Layout.OnRefreshComplete();
                                topicDetailAdapter.notifyDataSetChanged();
                                break;
                            case ZAN://赞
                                try {
                                    JSONObject jsonObject = new JSONObject((String) msg.obj);
                                    if (jsonObject != null) {
                                        String error_code = jsonObject.getString("err_code");
                                        if ("0".equals(error_code)) {
                                            //赞
                                            zan++;
                                            is_praised = true;
                                            college_topic_item_zan.setCompoundDrawables(drawable1, null, null, null);
                                            college_topic_item_zan.setText((Integer.parseInt((String) college_topic_item_zan.getText()) + 1) + "");
                                            college_topic_item_zan.setTextColor(color);
                                        } else {
                                            //取消赞
                                            zan--;
                                            is_praised = false;
                                            college_topic_item_zan.setCompoundDrawables(drawable, null, null, null);
                                            college_topic_item_zan.setText((Integer.parseInt((String) college_topic_item_zan.getText()) - 1) + "");
                                            college_topic_item_zan.setTextColor(color1);
                                        }
                                    }
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }

                                break;
                            default:
                                break;
                        }
                    }
                    break;
                default:
                    break;
            }
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        blogid = getIntent().getStringExtra("blogid");
        initData();
        initView();
        firstOpen = true;
    }

    @Override
    protected void onResume() {
        super.onResume();
        if(firstOpen){
            getDataFromInterNet(page, ON_REFRESH, true);
        }else{
            getDataFromInterNet(page, ON_REFRESH, false);
        }
    }

    private void initData() {
        commentList = new ArrayList<>();
        topicDetailAdapter = new TopicDetailAdapter(TopicDetail.this, commentList, blogid, new TopicDetailAdapter.DeleteCommentListener() {
            @Override
            public void deleteCommentListener(final int position) {
                final MyConfirmDialog myConfirmDialog = new MyConfirmDialog(TopicDetail.this, TopicDetail.this.getResources().getString(R.string.delete_title));
                myConfirmDialog.setConfirmListener(new MyConfirmDialog.ConfirmListener() {
                    @Override
                    public void confirm() {
                        deleteComment(commentList.get(position).getComment_id(), handler, position);
                        myConfirmDialog.dismiss();
                    }
                });
                myConfirmDialog.show();
            }
        });
    }

    private void initView() {
        topic_detail_back.setOnClickListener(this);
        topic_detail_comment_layout.setOnClickListener(this);
//        topic_detail_share_ima.setOnClickListener(this);
        topic_detail_refresh_load_Layout.setMyPtrHandler(new MyPtrRefresh_LoadView.MyPtrHandler() {
            @Override
            public void onLoadMoreBegin(PtrFrameLayout frame) {
                getDataFromInterNet(++page, ON_LOAD, false);
            }

            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                getDataFromInterNet(page = 1, ON_REFRESH, false);
            }
        });
        headerView = LayoutInflater.from(this).inflate(R.layout.college_topic_item, null);
        college_topic_item_headLayout = (RelativeLayout) headerView.findViewById(R.id.college_topic_item_headLayout);
        college_topic_item_name = (TextView) headerView.findViewById(R.id.college_topic_item_name);
        college_topic_item_addr = (TextView) headerView.findViewById(R.id.college_topic_item_addr);
        college_topic_item_content = (TextView) headerView.findViewById(R.id.college_topic_item_content);
        college_topic_item_time = (TextView) headerView.findViewById(R.id.college_topic_item_time);
        college_topic_item_zan = (TextView) headerView.findViewById(R.id.college_topic_item_zan);
        college_topic_item_delete = (TextView) headerView.findViewById(R.id.college_topic_item_delete);
        college_topic_item_zan.setOnClickListener(this);
        college_topic_item_headLayout.setOnClickListener(this);
        college_topic_item_comment = (TextView) headerView.findViewById(R.id.college_topic_item_comment);
        college_topic_item_headIma = (RoundedImageView) headerView.findViewById(R.id.college_topic_item_headIma);
        myGridView = (MyGridView) headerView.findViewById(R.id.college_topic_item_gridView);
        myListView.addHeaderView(headerView);
        myListView.setAdapter(topicDetailAdapter);
    }

    @Override
    public void onClick(View v) {
        Intent intent = new Intent();
        switch (v.getId()) {
            case R.id.topic_detail_back:
                setReturn();
                break;
            case R.id.college_topic_item_headLayout:
                intent.setClass(this, PersonalPage.class);
                intent.putExtra("userId", topicDetailBean.getBlog().getUserid());
                startActivity(intent);
                break;
            case R.id.college_topic_item_zan:
                praise(blogid, handler);
                break;
            case R.id.topic_detail_comment_layout:
                //不是评论自己
                if (hasLoad()) {
                    intent.setClass(this, DeliverComment.class);
                    intent.putExtra("blogid", blogid);
                    startActivity(intent);
                } else {
                    login(this);
                }
                break;
//            case R.id.topic_detail_share_ima:
//
//                break;
            default:
                break;
        }
    }

    private void getDataFromInterNet(int page, int type, boolean waitingDialog) {
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("blogid", blogid);
        hashMap.put("page", String.valueOf(page));
        new InterNetController(TopicDetail.this, Constant.BLOGDETAIL, handler, hashMap, type, waitingDialog);
    }

    private void praise(String blogid, Handler handler) {
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("blogid", blogid);
        new InterNetController(TopicDetail.this, Constant.PRISEBLOG, handler, hashMap, ZAN, false);
    }

    private void deleteBlog(String blogid, Handler handler) {
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("blogid", blogid);
        new https.InterNetController(TopicDetail.this, Constant.DELETEBLOG, handler, hashMap, DELETE_BLOG);
    }

    //删除某一条评论
    private void deleteComment(String commentId, Handler handler, int position) {
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("comment_id", commentId);
        new https.InterNetController(TopicDetail.this, Constant.DELETECOMMENT, handler, hashMap, DELETE_COMMENT, position, false);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        MyLogUtils.e(TAG,"resultCode"+resultCode);
        if (resultCode == 2) {
            getDataFromInterNet(page, ON_REFRESH, true);
        }
    }

    @Override
    public void onBackPressed() {
        setReturn();
    }

    private void setReturn() {
        Intent i = new Intent();
        i.putExtra("zan", zan);
        i.putExtra("comment", comment);
        i.putExtra("is_praised", is_praised);
        i.putExtra("is_deleted", is_deleted);
        this.setResult(2, i);
        TopicDetail.this.finish();
    }
}
